package com.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pojo.Menu;
import com.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/menu")
public class MenuController {

	@Autowired
	private MenuService menuService;

	@GetMapping("/list")
	public String list(@RequestParam(defaultValue = "1") int pageNum,
					   @RequestParam(defaultValue = "10") int pageSize,
					   Model model) {
		PageHelper.startPage(pageNum, pageSize);
		List<Menu> menus = menuService.findAll();
		PageInfo<Menu> pageInfo = new PageInfo<>(menus);
		model.addAttribute("pageInfo", pageInfo);
		return "menu/MenuList";
	}

	@GetMapping("/add")
	public String addPage() {
		return "menu/MenuAdd";
	}

	@PostMapping("/insert")
	public String insert(Menu menu) {
		menuService.insert(menu);
		return "redirect:/menu/list";
	}

	@GetMapping("/edit/{id}")
	public String editPage(@PathVariable Integer id, Model model) {
		Menu menu = menuService.findById(id);
		model.addAttribute("menu", menu);
		return "menu/MenuEdit";
	}

	@PostMapping("/update")
	public String update(Menu menu) {
		menuService.update(menu);
		return "redirect:/menu/list";
	}

	@GetMapping("/delete/{id}")
	public String deleteMenu(@PathVariable Integer id) {
		menuService.deleteById(id);
		return "redirect:/menu/list";
	}
}
